<template>
  <div>
    <el-radio-group v-model="dataType" size="large">
      <el-radio-button label="sale_">销量</el-radio-button>
      <el-radio-button label="_money">销售额</el-radio-button>
    </el-radio-group>
    <el-select v-model="day">
      <el-option value="yesterday" label="昨天"></el-option>
      <el-option value="today" label="今天"></el-option>
      <el-option value="seven_days" label="前7天"></el-option>
      <el-option value="fourteen_days" label="前14天"></el-option>
      <el-option value="thirty_days" label="前30天"></el-option>
    </el-select>
  </div>
  <div class="pie" ref="pie"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
type EChartsOption = echarts.EChartsOption;

const dataType = ref("sale_");
const day = ref("yesterday");

const props = defineProps(["data"]);

var option: EChartsOption = (option = {
  title: {
    show: false,
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    orient: "vertical",
    left: "left",
  },
  series: [
    {
      name: "Access From",
      type: "pie",
      radius: ["50%", "70%"],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
});
const pie = ref<HTMLDivElement>();
let myChart: echarts.ECharts;

onMounted(() => {
  myChart = echarts.init(pie.value as HTMLDivElement);
});

// 当props.data 变成有数据的时候，才渲染数据
watch(
  () => props.data.length,
  (newVal) => {
    // @ts-ignore
    option.series[0].data = props.data.map((item) => ({
      name: item.name,
      value: item.sale_fourteen_days,
    }));
    myChart.setOption(option);
  }
);

watch([dataType, day], () => {
  // 从props.data 里面获取数据，重新渲染
  // @ts-ignore
  const data = props.data.map((item) => {
    const key =
      dataType.value === "sale_"
        ? dataType.value + day.value
        : day.value + dataType.value;
    console.log(key);
    return {
      name: item.name,
      value: item[key],
    };
  });
  // @ts-ignore
  option.series[0].data = data;
  myChart.setOption(option);
});
</script>

<style scoped>
.pie {
  height: 400px;
}
</style>
